<?php

  require_once('ProfileService.php');



  $obj = new DBConnection();


  //this is a built in function to start the session... doh
  session_start();


  // Clear the error message
  $error_msg = "";

  // If the user isnt logged in, try to log them in
  if (!isset($_SESSION['userid'])) {
		if (isset($_POST['submit'])) {

			  $mysqli = $obj->getDBC();


			  // Grab the user-entered log-in data
			  $user = $mysqli->real_escape_string(trim($_POST['user']));
			  $password = $mysqli->real_escape_string(trim($_POST['password']));

			  if (!empty($user) && !empty($password)) {


				  $service = new ProfileService();

				  $profile = $service->getLoginProfile($user, $password);

				  if($profile != null){


					  $_SESSION['userid'] = $profile->userId;
					  $_SESSION['username'] = $profile->username;
					  $_SESSION['profile'] = serialize($profile);

					  setcookie('userid', $row[Constants::USER_ID], time() + (60 * 60 * 24 * 30));    // expires in 30 days
					  setcookie('username', $row[Constants::USER_NAME], time() + (60 * 60 * 24 * 30));  // expires in 30 days

					  $homeUrl = 'http://';
					  $dir = dirname($_SERVER['PHP_SELF']);
					  if($dir == '\\'){
						  $homeUrl .=  $_SERVER['HTTP_HOST'] . '/index.php';
					  }else{
						  $homeUrl .=  $_SERVER['HTTP_HOST'] . $dir . '/index.php';
					  }
					  header('Location: ' . $homeUrl);//put the home url in the header
				}
				else {
					  // The username/password are incorrect so set an error message
					  $error_msg = 'Sorry, you must enter a valid username and password to log in.';
				}
			  }
			  else {
					// The username/password weren't entered so set an error message
					$error_msg = 'Sorry, you must enter your username and password to log in.';
			  }
		}
  }

  // Insert the page header
  $page_title = 'Log In';
  require_once('header.php');

  // If the session var is empty, show any error message and the log-in form; otherwise confirm the log-in
  if (empty($_SESSION['userid'])) {
    echo '<p class="error">' . $error_msg . '</p>';
	?>

	  <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
		<fieldset>
		  <legend>Log In</legend>
		  <label for="user">Username:</label>
		  <input type="text" name="user" value="<?php if (!empty($user)) echo $user; ?>" /><br />
		  <label for="password">Password:</label>
		  <input type="password" name="password" />
		</fieldset>
		<input type="submit" value="Log In" name="submit" />
	  </form>

  <?php
  }
  else {
    // Confirm the successful log-in
    echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '.</p>');
  }
?>

<?php
  // Insert the page footer
  require_once('footer.php');
?>
